package util

import "time"

// RetryWithTimeout 用时有界的重试
func RetryWithTimeout(f func() error, timeout time.Duration, interval time.Duration) error {
	deadline := time.Now().Add(timeout)
	var err error
	for time.Now().Before(deadline) {
		err = f()
		if err == nil {
			return nil
		}
		time.Sleep(interval)
	}
	return err
}

// 默认重试间隔和超时时间的用时有界重试
func RetryWithDefaultTimeoutAndInterval(f func() error) error {
	const timeout = time.Minute
	const interval = time.Second
	return RetryWithTimeout(f, timeout, interval)
}

// 次数有界的重试
func RetryWithCount(f func() error, count int, interval time.Duration) error {
	for i := 0; i < count; i++ {
		err := f()
		if err == nil {
			return nil
		}
		time.Sleep(interval)
	}
	return nil
}

// 无限重试
func RetryForever(f func() error, interval time.Duration) {
	for {
		err := f()
		if err == nil {
			return
		}
		time.Sleep(interval)
	}
}
